﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RH.Common.Extensions;
using RH.Domain;
using RH.Web.ViewModels;
using RH.Web.Utility;
using AutoMapper;
using System.Text;

namespace RH.Web.Areas.Admin.Controllers
{
    public class UtilityController : BaseController
    {
		private AppEntities _Context = new AppEntities();
        
		#region Constructors
		public UtilityController()
		{
		}

		public UtilityController(UserViewModel currentUser)
			: base(currentUser)
        {
        }
		#endregion Constructors

		#region Action Methods
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public String SendFailedEmail()
        {            
            var query = from P in _Context.EmailMessages where !P.IsSent select P;
            int successCount = 0;
            int failedCount = 0;
            StringBuilder errors = new StringBuilder(10);
            List<EmailMessage> messages = query == null || query.Count() == 0 ? new List<EmailMessage>() : query.ToList();
            foreach (EmailMessage message in messages)
            {
                try
                {
                    message.AttemptedOn = DateTime.Now;
                    RH.Common.Mail.MailManager.SendMail(message.ToEmail, message.CC, message.BCC, message.FromEmail, message.Subject, message.Message);
                    message.IsSent = true;
                    successCount++;
                }
                catch (Exception ex)
                {
                    errors.AppendFormat("{0}<br/><br/>", ex.Message);
                    //lblMessage.Text = ex.Message;
                    //lblMessage.Text += "<br/>" + ex.StackTrace;

                    //break;
                    failedCount++;
                }
            }
            _Context.SaveChanges();
            //if (errors.Length > 0)
            //    lblMessage.Text = errors.ToString();

            //lblMessage.Text += String.Format("Total {0} emails sent and {1} failed", successCount, failedCount);

            var result = new
            {
                SuccussMessage = String.Format("Total {0} emails sent and {1} failed", successCount, failedCount),
                ErrorMessage = String.Format("<div class='{0}'>{1}</div>", AppConstants.UI.ERROR_MESSAGE_CLASS, errors.ToString())
            };
            return result.ToJSON();            
        }

        public ActionResult BackupDb()
        {
            return View();
        }

        /// <summary>
        /// Backs up the currently using database and stores in a downloadable location
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public String GenerateBackup()
        {
            String directory = Server.MapPath(AppConstants.Directories.TEMP);
            if (!System.IO.Directory.Exists(directory))
                System.IO.Directory.CreateDirectory(directory);

            String fileName = System.IO.Path.Combine(directory
                , String.Format("{0}_DB_{1}.sql", ConfigReader.SiteName, DateTime.Now.ToString("dd-MM-yyyy hhmmtt")));


            UtilityDAO dao = new UtilityDAO();
            dao.BackupDatabase(fileName);

            return String.Format("{0}/{1}", AppConstants.Directories.TEMP, System.IO.Path.GetFileName(fileName)).UrlEncode();
        }

        public ActionResult DownloadBackup(String file)
        {
            String tempDirectory = Server.MapPath(AppConstants.Directories.TEMP);

            String fileName = Server.MapPath(file.UrlDecode());

            ///Files without the temp directory and only *.sql files can be downloaded through this controller
            if (String.Compare(tempDirectory, System.IO.Path.GetDirectoryName(fileName), true) != 0
                || System.IO.Path.GetExtension(fileName).ToLower() != ".sql")
                throw new ArgumentException(String.Format("File {0} Cannot be downloaded", file.UrlDecode()));

            ///Intentionally keeping the temp database backup file.
            return File(fileName, "text/plain", System.IO.Path.GetFileName(fileName));

        }

		#endregion Action Methods
		
		#region Helper Methods

        #endregion			
    }
}
